package com.dragon.modules.yuegou.utils;

public class BitCodeUtils {

	private static final int[] CODE_MATRIX = { 
			0b00000000000000000000000000000001,
			0b00000000000000000000000000000010,
			0b00000000000000000000000000000100,
			0b00000000000000000000000000001000,
			0b00000000000000000000000000010000,
			0b00000000000000000000000000100000,
			0b00000000000000000000000001000000,
			0b00000000000000000000000010000000,
			0b00000000000000000000000100000000,
			0b00000000000000000000001000000000,
			0b00000000000000000000010000000000,
			0b00000000000000000000100000000000,
			0b00000000000000000001000000000000,
			0b00000000000000000010000000000000,
			0b00000000000000000100000000000000,
			0b00000000000000001000000000000000,
			0b00000000000000010000000000000000,
			0b00000000000000100000000000000000,
			0b00000000000001000000000000000000,
			0b00000000000010000000000000000000,
			0b00000000000100000000000000000000,
			0b00000000001000000000000000000000,
			0b00000000010000000000000000000000,
			0b00000000100000000000000000000000,
			0b00000001000000000000000000000000,
			0b00000010000000000000000000000000,
			0b00000100000000000000000000000000,
			0b00001000000000000000000000000000,
			0b00010000000000000000000000000000,
			0b00100000000000000000000000000000,
			0b01000000000000000000000000000000,
			0b10000000000000000000000000000000
	};
	
	/**
	 * 设置编码在某一位上的比特值
	 * @param code 32位编码
	 * @param index 下标（0~31，从右往左数）
	 * @param bit 比特值，true表示1，false表示0
	 * @return
	 */
	public static int set(int code, int index, boolean bit) {
		int mask = CODE_MATRIX[index];
		if(bit) {
			return code | mask;
		}else {
			return code & ~mask;
		}
	}

	/**
	 * 获取编码在某一位上的比特值
	 * @param code 32位编码
	 * @param index 下标（0~31，从右往左数）
	 * @return 比特值，true表示1，false表示0
	 */
	public static boolean get(int code, int index) {
		return (code & CODE_MATRIX[index]) != 0;
	}
	
	public static boolean hasFactors(int code, int... factors) {
		for (int factor : factors) {
			if ((code & factor) == 0) {
				return false;
			}
		}
		return true;
	}

	public static boolean hasAnyFactors(int code, int... factors) {
		for (int factor : factors) {
			if ((code & factor) != 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 编码是否有某个因素
	 * @param code 32位编码
	 * @param factor 因素
	 * @return 如果编码有某个因素则返回true，否则返回false
	 */
	public static boolean hasFactor(int code, int factor) {
		return (code & factor) != 0;
	}
}